import subprocess
import uuid
import os
import base64
from datetime import datetime
from dateutil.relativedelta import relativedelta
from pathlib import Path

import logging

TMP_FOLDER = Path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "tmp"))
TMP_FOLDER.mkdir(parents=True, exist_ok=True)


def get_days_count_for_period(months_period: int, from_date: str = None) -> int:
    """
    Вычисление количества дней для указанного периода в месяцах.

    Аргументы:
        months_period (int): Период времени в месяцах. (Сколько месяцев прибавить к дате)
        from_date (str, optional): Дата начала периода в формате "дд.мм.гггг". Если не указывать то используется текущая дата.

    Возвращает:
        int: Количество дней в заданном периоде времени.
    """

    if not from_date:
        from_date: datetime = datetime.now()
    else:
        if '-' in from_date:
            from_date = from_date.replace('-', '.')
        from_date: datetime = datetime.strptime(from_date, "%d.%m.%Y")
    
    rd = relativedelta(months=months_period)
    target_date = from_date + rd
    return (target_date - from_date).days


class LicenseGenerator:
    def __init__(self, jsonRootSettings) -> None:
        settings = jsonRootSettings["tools"]["licensegenerator"]
        
        self.LICENSE_GENERATION_TOOL_PATH: Path = Path(settings["tool_executable"])


    def gen(self, jsonData):
        filename = None
        # Generate random file name
        filename = str(TMP_FOLDER / f"{os.urandom(16).hex()}.lickey")
        
        def get_(key, default=None, required=False):
            if key in jsonData:
                return jsonData[key]
            else:
                if required:
                    raise Exception(f"{key} is required")
                return default
        
        license_count = get_("license_count", "1")
        start_date = get_("start_date")
        company = str(get_("company", required=True)).strip()
        days = get_("days", required=True)
        days = get_days_count_for_period(days / 30, start_date)
        
        demo = get_("demo", False)
        company_uuid = get_("company_uuid")
        if not company_uuid:
            company_uuid = str(uuid.uuid4())
        
        company = company.replace('"', '\\"')
        
        command = f'{self.LICENSE_GENERATION_TOOL_PATH} --show-xml --output="{filename}" --id=102 --license-count={license_count} --company-uid="{company_uuid}" --company="{company}" --days={days} '
        command += f'{"--demo" if demo else ""} '
        if start_date:
            command += f'--start-date="{start_date}" '
            
        logging.info(command)

        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        stdout, stderr = process.communicate()
        
        process.wait()
        return stdout.decode('utf-8'), stderr.decode('utf-8'), filename